import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class leetCodeTest02 {
    public static void main(String[] args) {
        int[][] intervals = {{1, 4},{0,4}};
        int[][] ans = merge(intervals);
        for(int i = 0;i<ans.length;i++){
            System.out.println("["+ans[i][0]+","+ans[i][1]+"]");
        }
    }
        public static int[][] merge(int[][] intervals) {
            Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
            int flag1=intervals[0][0];
            int flag2=intervals[0][1];
            int[] element = {flag1,flag2};
            List<int[]> ans = new ArrayList<>();
            if(intervals.length == 1)ans.add(element);
            else{
                for(int i = 0;i < intervals.length-1;i++){
                    if(flag2 >= intervals[i+1][0]){
                        if(flag2<intervals[i+1][1])flag2=intervals[i+1][1];
                    }
                    else{
                        element = new int[2];
                        element[0] = flag1;
                        element[1] = flag2;
                        flag1 = intervals[i+1][0];
                        flag2 = intervals[i+1][1];
                        ans.add(element);
                    }
                }
                element = new int[2];
                element[0] = flag1;
                element[1] = flag2;
                ans.add(element);

            }

            int[][] an = new int[ans.size()][2];
            for(int i = 0;i<ans.size();i++){
                an[i] = ans.get(i);
            }
            return an;

        }
}
